/**
 * @(#) CostsMediator.as
 *
 * @date		2015. 02. 25.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	교통비  신청 - Mediator
 * 				교통비 을 조회하고 신청하는 Presentation Logic을 관리 
 */
package com.skt.common_hr.biztrip.view
{
	import com.skt.common_hr.biztrip.BizTripFacade;
	import com.skt.common_hr.biztrip.events.MemberAdjustEvent;
	import com.skt.common_hr.biztrip.model.BizTripBudgetProxy;
	import com.skt.common_hr.biztrip.model.CostsApprovalProxy;
	import com.skt.common_hr.biztrip.model.CostsBizTripProxy;
	import com.skt.common_hr.biztrip.model.DailyCostProxy;
	import com.skt.common_hr.biztrip.model.vo.AdjustBaseVO;
	import com.skt.common_hr.biztrip.model.vo.AdjustDataPackage;
	import com.skt.common_hr.biztrip.model.vo.BizTripListVO;
	import com.skt.common_hr.biztrip.model.vo.BizTripMemberVO;
	import com.skt.common_hr.biztrip.model.vo.BizTripPlaceVO;
	import com.skt.common_hr.biztrip.model.vo.BizTripSummaryVO;
	import com.skt.common_hr.biztrip.model.vo.DailyCostVO;
	import com.skt.common_hr.biztrip.model.vo.MemberAdjustVO;
	import com.skt.common_hr.biztrip.model.vo.MemberCarfareVO;
	import com.skt.common_hr.biztrip.model.vo.MemberDetailCostVO;
	import com.skt.common_hr.biztrip.view.components.CostsAdjustView;
	import com.skt.common_hr.biztrip.view.components.CostsBizTrip;
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.approval.RequestApprovalMediator;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.memberselector.MemberSelectorMediator;
	import com.skt.common_hr.common.memberselector.MemberVO;
	import com.skt.common_hr.common.puremvc.CommonMediator;
	import com.wcl.components.Hourglass;
	import com.wcl.utils.DateUtil;
	import com.wcl.utils.StringUtil;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.core.IFlexDisplayObject;
	import mx.managers.PopUpManager;
	import mx.resources.ResourceManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;

	public class CostsMediator extends CommonMediator
	{
		public static const NAME:String = "CostsMediator"; 


		private var key1:String;
		private var key2:String;
		private var _currentKey:String;
		private var _bWaitingApproval:Boolean = false;
		private var TRSTATUS:String = "11";
		private var bModify:Boolean = true;
		private var bReadOnly:Boolean = false;

		private var adjustBase:AdjustBaseVO;
		private var memberCarfare:ArrayCollection = new ArrayCollection();
		private var memberDetailCost:ArrayCollection= new ArrayCollection();
		

		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
        public function CostsMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
            view.callLater(initView);
        }
 		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		private function initView():void
 		{
			//loadBizTripList();
			//set event handlers...

			view.addEventListener(CostsBizTrip.CHANGED_TERM, onChangedTerm);
			view.addEventListener(CostsBizTrip.ADD_MEMBER, onAddMember);
			view.addEventListener(CostsBizTrip.DEL_MEMBER, onDelMember);
			//view.addEventListener(CostsBizTrip.DEL_RECORD, onDelRecord);
			view.addEventListener(CostsBizTrip.SAVE, onSave);
			view.addEventListener(CostsBizTrip.APPROVAL, onApproval);
			view.addEventListener(CostsBizTrip.CANCEL, onInputCancel);
			
			view.addEventListener(MemberAdjustEvent.ADJUST_MEMBER, onAdjustMember);
 		}
 		
 		override protected function clearView():void
 		{
 			trace("clear 국내출장");
 			key1 = "";
 			key2 = "";
			initViewData();
 		}
 		
 		
		/**
		* 신규 생성일 경우 
		*	- View를 위한 기본 테이블들을 초기화 한다.
		* @param
		* @return void
		*/
		private function initViewData():void
		{
 			key1 = "";
 			key2 = "";
 			trace("initViewData");
			// 출장 master테이블 기본 데이터 설정
			var summary:BizTripSummaryVO = new BizTripSummaryVO;
			summary.GWAREKEY01 = "";
			summary.GWAREKEY02 = "";
			summary.TRSTATUS = "11";
			summary.TRSTATX = ResourceManager.getInstance().getString(commonFacade.bundle, "STATUS_PLANNING", null, Variables.current_locale);
			summary.BEGDA = DateUtil.todayNoTime();
			summary.ENDDA = DateUtil.todayNoTime();
			summary.TRTYPE = "04";
			summary.TTEXT = "여비교통비"//ResourceManager.getInstance().getString(commonFacade.bundle, "DOMESTIC_BIZTRIP", null, Variables.current_locale);
			summary.IPERNR  = Variables.myPernr;
			summary.PURPOSE = "";
			summary.MNUM = 1;
			summary.TRGUBUN = "1";
			summary.TRTITLE = "여비교통비 신청";
			view.summary = summary;
			// 출장지  테이블 기본설정
			var placeList:ArrayCollection = new ArrayCollection();
			var place:BizTripPlaceVO = new BizTripPlaceVO;
			place.BEGDA = DateUtil.todayNoTime();
			place.ENDDA = DateUtil.todayNoTime();
			place.BREN = "";
			placeList.addItem(place);
			view.placeList = placeList;
			
			// 출장자 테이블 기본설정
			view.memberList = new ArrayCollection();
			var member:BizTripMemberVO = new BizTripMemberVO();
			member.PERNR = Variables.myPernr;
			member.ENAME = Variables.myName;
			member.ORGTX = Variables.myOrg;
			//member.JWTXT = Variables.
			member.BEGDA = DateUtil.todayNoTime();
			member.ENDDA = DateUtil.todayNoTime();
			member.WDAY = DateUtil.DateDiff(member.BEGDA, member.ENDDA);
			view.memberList.addItem(member);

			view.memberAdjustList = new ArrayCollection();
			memberCarfare = new ArrayCollection();
			memberDetailCost = new ArrayCollection();
			
			view.totalAmount = 0;
			
			view.doAdjustMode();
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Proxy 연동   Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		
		/**
		*  국내 출장 데이터를 로드한다. 
		* @param
		* @return void
		*/
		private function loadCostsBizTrip(vo:BizTripListVO):void
		{
			key1 = vo.GWAREKEY01;
			key2 = vo.GWAREKEY02;
			TRSTATUS = vo.TRSTATUS;

			var proxy:CostsBizTripProxy = facade.retrieveProxy(CostsBizTripProxy.NAME) as CostsBizTripProxy;
			proxy.load(key1, key2);
			trace("국내출장 loading keys: " + key1 + ", " + key2);
		}
		
		/**
		*  가용예산을 로드한다.
		* @param
		* @return void
		*/
		private function loadBudget(pernr:String):void
		{
			var budgetProxy:BizTripBudgetProxy = facade.retrieveProxy(BizTripBudgetProxy.NAME) as BizTripBudgetProxy;
			budgetProxy.load(pernr, BizTripFacade.TYPE_COSTS_BIZTRIP);
		}
		
		
		
		private function onLoadBizTripData(proxy:CostsBizTripProxy):void
		{
			view.summary 			= proxy.summary;			// 출장요약
			view.placeList 			= proxy.places;				// 출장지
			view.memberList 		= proxy.members;			// 출장자
			view.memberAdjustList 	= proxy.memberAdjusts;		// 출장자별 정산 요약
			//trace("trstatus: " + view.summary.TRSTATUS);
			alignMemberData();
			
			// 정산기준 
			if(proxy.adjustBase.length>0) {
				view.budget = proxy.adjustBase.getItemAt(0).WERT1;
				adjustBase = proxy.adjustBase.getItemAt(0) as AdjustBaseVO;
			}			
			else {
				adjustBase = new AdjustBaseVO();
			}
			loadBudget(proxy.summary.IPERNR);
			
			memberCarfare = proxy.memberCarfare;				// 출장자별 일비, 차량비용
			memberDetailCost = proxy.memberDetailCost			// 출장자별 세부 정산
			setDistance();
			
			sumTotalAmount();
			if(!bReadOnly) {
				setViewStatus(view.summary.TRSTATUS);
			}
			else {
				setViewStatus2(view.summary.TRSTATUS); 
			}
			trace("TRSTATUS:  "+view.summary.TRSTATUS);
		}
		
		private function setDistance():void
		{
			for each(var adjust:MemberAdjustVO in view.memberAdjustList) {
				var carfare:MemberCarfareVO  = findCarfare(adjust.PERNR);
				if(carfare!=null) {
					adjust.DRIKM = carfare.DRIKM;
				}
			}
		}


		private function alignMemberData():void
		{
			var tmpAdjustList:ArrayCollection = new ArrayCollection;
			for each(var member:BizTripMemberVO in view.memberList) {
				var adjust:MemberAdjustVO= this.findMemberAdjust(member.PERNR);
				if(!adjust) {
					adjust = new MemberAdjustVO;
					adjust.PERNR = member.PERNR;
					adjust.ENAME = member.ENAME;
				}
				tmpAdjustList.addItem(adjust);
			}
			view.memberAdjustList = tmpAdjustList;
		}
		
 		private function onLoadBudget(proxy:BizTripBudgetProxy):void
 		{
 			view.budget = proxy.budget;
 			if(adjustBase == null) {
 				adjustBase = new AdjustBaseVO();
 			}
 			adjustBase.KOSTL = proxy.KOSTL;
 			adjustBase.WERT1 = proxy.budget;
 			adjustBase.WAERS = proxy.wares;
 			adjustBase.KDATE = new Date();
 			adjustBase.KURSF01 = 0;
 			adjustBase.KURSF02 = 0;
 		}
		
		
		
		
		
		
		
		
		
		
		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return [
					BizTripFacade.READONLY_COSTS_VIEW,
					BizTripFacade.MODIFY_COSTS_VIEW,
					BizTripFacade.LOAD_COSTS_BIZTRIP_COMPLETE,
					BizTripFacade.LOAD_COSTS_BIZTRIP_FAILED,
					BizTripFacade.SAVE_COSTS_BIZTRIP_COMPLETE,
					BizTripFacade.SAVE_COSTS_BIZTRIP_FAILED,
					BizTripFacade.APP_COSTS_BIZTRIP_COMPLETE,
					BizTripFacade.APP_COSTS_BIZTRIP_FAILED,
					//BizTripFacade.SELECTED_MEMBER,
					MemberSelectorMediator.SELECTED_MEMBER,
					BizTripFacade.LOAD_BUDGET_COMPLETE,
					BizTripFacade.LOAD_BUDGET_FAILED,
					BizTripFacade.CONFIRM_COSTS_ADJUST_INPUT,
					BizTripFacade.CANCEL_COSTS_ADJUST_INPUT,
					RequestApprovalMediator.APPROVAL_CANCEL,
					RequestApprovalMediator.APPROVAL_COMPLETE,
					DailyCostProxy.LOAD_DAILY_COST_MULTI_COMPLETE,
					DailyCostProxy.LOAD_DAILY_COST_MULTI_FAILED
					];
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			switch(note.getName()) 
			{
				case BizTripFacade.READONLY_COSTS_VIEW:
					bActivated = true;
					bReadOnly = true;
					loadCostsBizTrip( note.getBody() as BizTripListVO);
					break;
				case BizTripFacade.MODIFY_COSTS_VIEW:
					bActivated = true;
					bReadOnly = false;
					initViewData(); 
					if(note.getBody()) {
						loadCostsBizTrip( note.getBody() as BizTripListVO);
					}
					else {
						view.callLater(setViewStatus, [view.summary.TRSTATUS]);
						commonFacade.setStatusMessage("STATUS_START_COSTS_BIZTRIP");
					}
					break;
				case BizTripFacade.LOAD_COSTS_BIZTRIP_COMPLETE:
					onLoadBizTripData(note.getBody() as CostsBizTripProxy);
					commonFacade.setStatusMessage("STATUS_LOAD_COSTS_BIZTRIP");
					break;
				case BizTripFacade.LOAD_COSTS_BIZTRIP_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "("+note.getBody().retCode+")"+note.getBody().retText, null,
										"ALERT_TITLE_ERROR");
					break;
				case BizTripFacade.SAVE_COSTS_BIZTRIP_COMPLETE:
					commonFacade.setStatusMessage("STATUS_SAVE_COSTS_BIZTRIP");
					if(_bWaitingApproval) {
						_bWaitingApproval = false;
						key1 = _currentKey = CostsBizTripProxy(note.getBody()).outKey;
						//trace(_currentKey);
						view.summary.GWAREKEY01 = _currentKey;
						CommonAlert.showMsgYesNo(commonFacade.bundle, "ALERT_ASK_APPROVAL", null, "ALERT_TITLE_INFO", null,
							execApproval, null );						
							
					}
					else {
						bActivated = false;
						facade.sendNotification(BizTripFacade.CHANGE_VIEW_BIZTRIP_LIST, this);
					}
					break;
				case BizTripFacade.APP_COSTS_BIZTRIP_COMPLETE:
					Hourglass.remove();
					CommonAlert.showMessage(commonFacade.bundle, "ALERT_SUCCEED_APPROVAL", null,
										"ALERT_TITLE_ERROR");
					clearView();
					facade.sendNotification(BizTripFacade.CHANGE_VIEW_BIZTRIP_LIST, this);
					break;
				case BizTripFacade.SAVE_COSTS_BIZTRIP_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "("+note.getBody().retCode+")"+note.getBody().retText, null,
										"ALERT_TITLE_ERROR");
					if(_bWaitingApproval) {
						_bWaitingApproval = false;
					}
					break;
				case BizTripFacade.LOAD_BUDGET_COMPLETE:
					onLoadBudget(note.getBody() as BizTripBudgetProxy);
					break;
				case MemberSelectorMediator.SELECTED_MEMBER:
				//case BizTripFacade.SELECTED_MEMBER:
					if(bActivated) {
						if(findMember(MemberSelectorMediator(note.getBody()).selectedMember.PERNR)>-1) {
							CommonAlert.showMessage(commonFacade.bundle, "ALERT_ALREADY_MEMBER", null,
											"ALERT_TITLE_ERROR");
						}
						else {
							addMemberList(MemberSelectorMediator(note.getBody()).selectedMember);
						}
					}
					break;
				case BizTripFacade.CONFIRM_COSTS_ADJUST_INPUT:
					onConfirmAdjustInput(note.getBody() as AdjustDataPackage);
					break;
				case BizTripFacade.CANCEL_COSTS_ADJUST_INPUT:
					break;
				case RequestApprovalMediator.APPROVAL_COMPLETE:					// 결재 요청  성공
					bActivated = false;
					facade.sendNotification(BizTripFacade.CHANGE_VIEW_BIZTRIP_LIST, this);
					break;
				case RequestApprovalMediator.APPROVAL_CANCEL:					// 결재 요청 취소
					bActivated = true;
					//cancelApproval(_currentKey);
					break;
				case DailyCostProxy.LOAD_DAILY_COST_MULTI_COMPLETE:
					setDailyCost(note.getBody() as DailyCostProxy);
					break;
				case DailyCostProxy.LOAD_DAILY_COST_MULTI_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "(" + note.getBody().errCode + ")" + note.getBody().errText); 
					break;
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}
		
		









 
 
 
 
 
 
 
 
 
 
 
 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	저장관련 함수.....
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		
		private function onSave(event:Event):void
		{
			alignPlaceDate();
			if(!validData()) return;

			saveBizTrip(false);
		}
		
		private function onApproval(event:Event):void
		{
			alignPlaceDate();
			if(!validData()) return;
			_bWaitingApproval = true;
			saveBizTrip(true);
		}
		
		private function saveBizTrip(bApproval:Boolean):void
		{
			var proxy:CostsBizTripProxy = facade.retrieveProxy(CostsBizTripProxy.NAME) as CostsBizTripProxy;
			trace("saving keys = " + key1 +", " + key2);
			
			
			if(view.summary.TRPAYC == "") {	// 정산 안함
				/////////////////////////////////////////////////////////////////////////////
				// 사용 안함
//				proxy.save(bApproval, false, false, "11", key1, key2, 
//						toSaveFormatSummary(view.summary),				// 출장 요약 
//						toSaveFormatPlaceList(view.placeList), 			// 출장지
//						toSaveFormatMemberList(view.memberList),			// 출장자
//						new Array(),					// 정산기준
//						new Array(),			// 출장비 내역
//						new Array()			// 출장자별 세부내역
//						);
			}
			else {		// 정산포함
				//divideAmount();
				proxy.save(bApproval, true, false, "21", key1, key2, 
						toSaveFormatSummary(view.summary),				// 출장 요약 
						toSaveFormatPlaceList(view.placeList), 			// 출장지
						toSaveFormatMemberList(view.memberList),		// 출장자
						toSaveFormatAdjustBase(adjustBase),				// 정산기준
						toSaveFormatCarfare(memberCarfare),				// 출장비 내역
						toSaveFormatMemberDetailCost(memberDetailCost)				// 출장자별 세부내역
						/*
						recordToArray(view.summary),				// 출장 요약 
						collectionToArray(view.placeList), 			// 출장지
						collectionToArray(view.memberList),			// 출장자
						recordToArray(adjustBase),					// 정산기준
						collectionToArray(memberCarfare),			// 출장비 내역
						collectionToArray(memberDetailCost)			// 출장자별 세부내역
						*/
						);
			}
		}
		
		private function execApproval():void
		{
 			var approval:RequestApprovalMediator = facade.retrieveMediator(RequestApprovalMediator.NAME) as RequestApprovalMediator;
 			if(approval==null) {
 				approval = new RequestApprovalMediator(view, "03");
 				facade.registerMediator(approval);
 			}
 			bActivated = false;
 			var appProxy:CostsApprovalProxy = facade.retrieveProxy(CostsApprovalProxy.NAME) as CostsApprovalProxy;
 			appProxy.key = _currentKey;
 			appProxy.summary 			= view.summary;
 			appProxy.placeList 			= view.placeList;
 			appProxy.memberList 		= view.memberList;
 			appProxy.adjustBase 		= adjustBase;
 			appProxy.memberCarfare 		= memberCarfare;
 			appProxy.memberDetailCost 	= memberDetailCost;
 			appProxy.memberAdjustList	= view.memberAdjustList;
 			appProxy.amount				= view.totalAmount;
			appProxy.appType = (view.summary.TRPAYC == "") ? false : true;
			
			var bCheckTRPAYC:Boolean = false;
			if(view.summary.TRPAYC == "") {	// 정산 안함
				bCheckTRPAYC = false;
			} else {
				bCheckTRPAYC = true;
			}			
			approval.execRequest(view, appProxy, bCheckTRPAYC); // bTRPAYC : 정산포함여부
		}

		private function alignPlaceDate():void
		{
			// 각 출장지별  End Date 계산
			for(var i:int=0; i<5; i++) {
				if((i+1)>=view.placeList.length) {
					view.placeList.getItemAt(i).ENDDA = view.summary.ENDDA;
					break;
				}
				var endda:Date = new Date(view.placeList.getItemAt(i+1).BEGDA);
				endda.date -= 1;
				if(Number(endda)<Number(view.placeList.getItemAt(i).BEGDA)) {
					endda = new Date(view.placeList.getItemAt(i).BEGDA);
				}
				view.placeList.getItemAt(i).ENDDA = endda;
			}
			
		}

		private function validData():Boolean
		{
			if(view.summary.TRTITLE==null || view.summary.TRTITLE.length<=0) {
				CommonAlert.showMessage(commonFacade.bundle, "ALERT_INVALID_TITLE", null, "ALERT_TITLE_INVALID_DATA", view);
				return false;
			}
			if( !checkPlaceDate() ) {
				CommonAlert.showMessage(commonFacade.bundle, "ALERT_INVALID_PLACE_DATE01", null, "ALERT_TITLE_INVALID_DATA", view);
				return false;
			}
			
			if( !checkPlaces() ) {
				CommonAlert.showMessage(commonFacade.bundle, "ALERT_INVALID_PLACE", null, "ALERT_TITLE_INVALID_DATA", view);
				return false;
			}

			if( !checkMemberList() ) {
				CommonAlert.showMessage(commonFacade.bundle, "ALERT_INVALID_MEMBER", null, "ALERT_TITLE_INVALID_DATA", view);
				return false;
			}
			return true;
		}


		
		private function divideAmount():void
		{
			if(adjustBase.WERT1!=0) 
				adjustBase.WERT1 /= 100;
			for each(var item1:MemberCarfareVO in memberCarfare)
			{
				if(item1.PDRPY!=0) 
					item1.PDRPY /=100;
				if(item1.UNITAMT!=0)
					item1.UNITAMT /= 100;
				if(item1.DAYPY!=0)
					item1.DAYPY /= 100;
			}
			
			for each(var item2:MemberDetailCostVO in memberDetailCost)
			{
				if(item2.AMT!=0) 
					item2.AMT /=100;
			}
			
		}
		private function checkPlaceDate():Boolean
		{

			for(var i:int=0; i<view.placeList.length; i++) 
			{
				if(Number(view.placeList.getItemAt(i).BEGDA) < Number(view.summary.BEGDA) ||
					Number(view.placeList.getItemAt(i).ENDDA) < Number(view.summary.BEGDA) ||
					Number(view.placeList.getItemAt(i).BEGDA) > Number(view.summary.ENDDA) || 
					Number(view.placeList.getItemAt(i).ENDDA) > Number(view.summary.ENDDA)) 
					{
						//trace(view.placeList.getItemAt(i).BEGDA+","+view.placeList.getItemAt(i).ENDDA);
						return false;
					}
			}
			return true;
		}
		
		private function checkPlaces():Boolean
		{

			for(var i:int=0; i<view.placeList.length; i++) 
			{
				if(StringUtil.NVL(view.placeList.getItemAt(i).BREN)=="")
				{
					return false;
				}
			}
			return true;
		}
		
		private function checkMemberList():Boolean
		{
			for(var i:int=0; i<view.memberList.length; i++) {
				if(Number(view.memberList.getItemAt(i).BEGDA) < Number(view.summary.BEGDA) ||
					Number(view.memberList.getItemAt(i).ENDDA) < Number(view.summary.BEGDA) ||
					Number(view.memberList.getItemAt(i).BEGDA) > Number(view.summary.ENDDA) || 
					Number(view.memberList.getItemAt(i).ENDDA) > Number(view.summary.ENDDA)) {
						return false;
					}
			}
			return true;
		}


		private function setDailyCost(proxy:DailyCostProxy):void
		{
			var bCheck:Boolean = false;
			for each(var vo:DailyCostVO in proxy.costList) {
				var target:MemberAdjustVO = findMemberAdjust(vo.PERNR);
				var carfare:MemberCarfareVO = findCarfare(vo.PERNR);
				
				if(target!=null && carfare!=null) {
					if(target.DAYPY != vo.AMT) {
						//target.DAYPY = vo.AMT;
						bCheck = true;						
					}
					target.DAYPY = vo.AMT;
					carfare.DAYPY = vo.AMT;
				}				
			}
			sumTotalAmount();
			if(bCheck) {
				//CommonAlert.showMessage(commonFacade.bundle, "초과된 일비가 발생했습니다. \n상세입력에서 일비를 조정하시기 바랍니다.", null, "확인");
				CommonAlert.showMessage(commonFacade.bundle, "출장기간 변경으로 인해 일비가 조정되었습니다.", null, "확인");
			}
		}

		private function onInputCancel(event:Event):void
		{
			clearView();
			bActivated=false;
			facade.sendNotification(BizTripFacade.CHANGE_VIEW_BIZTRIP_LIST, this);
		}
		
	
		
		private var adjustMemberView:IFlexDisplayObject = null;
		private function onAdjustMember(event:MemberAdjustEvent):void
		{
			if(!adjustMemberView) {
 				adjustMemberView = PopUpManager.createPopUp(view, CostsAdjustView, true);
 				PopUpManager.centerPopUp(adjustMemberView);
	 			var mediator:CostsAdjustMediator = new CostsAdjustMediator(adjustMemberView);
	 			facade.registerMediator(mediator);
 			}
 			else {
 				PopUpManager.addPopUp(adjustMemberView, view, true);
 			}
			CostsAdjustView(adjustMemberView).setFocus();
 			if(view.viewStatus != CostsBizTrip.STATUS_READONLY_ALL) {
	 			facade.sendNotification(BizTripFacade.PERSONAL_COSTS_ADJUSTMENT, buildAdjustDataPackage(event.member));
	 		}
	 		else {
	 			facade.sendNotification(BizTripFacade.PERSONAL_COSTS_ADJUSTMENT_READONLY, buildAdjustDataPackage(event.member));
	 		}
		}
		
		private function onChangedTerm(event:Event):void
		{
			// 출장일정에 변경이 생겼으면 일비 재조정
			adjustDailyCost();
		}
		
		private function adjustDailyCost():void
		{
			var dailyMembers:Array = new Array();
			// 일비재조정-정산중일 때만
			if(view.bEditableAdjust) {
				for each(var member:BizTripMemberVO in view.memberList) {
					if(findMemberAdjust(member.PERNR).TRTICH == "X") {
						var dailyMember:Object = new Object();
						dailyMember.PERNR = member.PERNR;
						dailyMember.LAND1 = "";
						dailyMember.TRDAYS = DateUtil.DateDiff(member.BEGDA, member.ENDDA).toString();
						
						if(findMemberAdjust(member.PERNR).PCARC == 'X' || findMemberAdjust(member.PERNR).OCARC == 'X' || findMemberAdjust(member.PERNR).TCARC == 'X'){
							dailyMember.OIL = 'X';
						}else{
							dailyMember.OIL = '';
						}
//						dailyMember.OIL = findMemberAdjust(member.PERNR).PCARC;
//						dailyMember.OIL = findMemberAdjust(member.PERNR).OCARC;
//						dailyMember.OIL = findMemberAdjust(member.PERNR).TCARC;
						dailyMember.EGBN = findMemberAdjust(member.PERNR).EGBN;
						dailyMembers.push(dailyMember);
					}
				}
				if(dailyMembers.length>0) {
					loadDailyCost(dailyMembers);
				}
			}
		}


		private function loadDailyCost(memberList:Array):void
		{
			var proxy:DailyCostProxy = facade.retrieveProxy(DailyCostProxy.NAME) as DailyCostProxy;
			proxy.loadMulti(BizTripFacade.TYPE_COSTS_BIZTRIP, view.summary.BEGDA, memberList);	
		}
		
		private function onAddMember(event:Event):void
		{
			var mediator:MemberSelectorMediator;
			mediator = facade.retrieveMediator(MemberSelectorMediator.NAME) as MemberSelectorMediator;
			if(mediator==null) {
				mediator = new MemberSelectorMediator();
				facade.registerMediator(mediator);
			}
			mediator.exec(view.root);
		}
		
		private function onDelMember(event:Event):void
		{
			removeCarfare(view.deletedMember);
		}
		
		
		private function findMember(pernr:String):int
		{
			for (var i:int=0; i<view.memberList.length; i++) {
				if(view.memberList.getItemAt(i).PERNR == pernr) return i;
			}
			return -1;
		}
		
		
		
		
		private function addMemberList(member:MemberVO):Boolean
		{
			var vo:BizTripMemberVO = new BizTripMemberVO();
			vo.PERNR = member.PERNR
			vo.ENAME = member.ENAME;
			vo.ORGTX = member.STEXT;
			vo.JWTXT = member.JWTXT;
			vo.BEGDA = new Date(view.summary.BEGDA);
			vo.ENDDA = new Date(view.summary.ENDDA);
			vo.WDAY  = DateUtil.DateDiff(vo.BEGDA, vo.ENDDA); 
			view.memberList.addItem(vo);
			
			view.summary.MNUM = view.memberList.length;
			if(view.summary.TRPAYC == "X") {
				var ad:MemberAdjustVO = new MemberAdjustVO;
				ad.PERNR = member.PERNR;
				ad.ENAME = member.ENAME;
				view.memberAdjustList.addItem(ad);
			}
			return true;
		}
		
		
		private function blankRecord():BizTripPlaceVO
		{
			var rec:BizTripPlaceVO = new BizTripPlaceVO();
			rec.BEGDA = DateUtil.todayNoTime();
			rec.ENDDA = DateUtil.todayNoTime();
			return rec;
		}
 		
 		
 		
 		
 		
  		private function recordToArray(rec:*):Array
  		{
 			var arr:Array = new Array();
 			//trace(rec.PURPOSE);
			arr.push(rec.clone());
			return arr;
 		}
 		
		private function toSaveFormatSummary(vo:BizTripSummaryVO):Array
		{
			var arr:Array = new Array();
			var tmp:Object = new Object;
			tmp.GWAREKEY01	 = vo.GWAREKEY01;
			tmp.GWAREKEY02	 = vo.GWAREKEY02;
			tmp.TRSTATUS	 = vo.TRSTATUS;
			tmp.TRSTATX	 	= vo.TRSTATX;
			tmp.TRTYPE	 	= vo.TRTYPE;
			tmp.TTEXT	 	= vo.TTEXT;
			tmp.BEGDA	 	= DateUtil.toBasicString(vo.BEGDA);
			tmp.ENDDA	 	= DateUtil.toBasicString(vo.ENDDA);
			tmp.TRTITLE		= vo.TRTITLE;
			tmp.BTEXT		= vo.BTEXT;
			tmp.MNUM		= vo.MNUM.toString();
			tmp.TRPAYC		= vo.TRPAYC;
			tmp.IPERNR		= vo.IPERNR;
			tmp.TRTEXT		= vo.TRTEXT;
			tmp.PURPOSE		= vo.PURPOSE;
			
			tmp.TRGUBUN		= vo.TRGUBUN;
			arr.push(tmp);
			return arr;
		} 		

		private function toSaveFormatPlaceList(coll:ArrayCollection):Array
		{
			var arr:Array = new Array();
			for each(var place:BizTripPlaceVO in coll)
			{
				var tmp:Object = new Object;
				tmp.SEQNO	 = place.SEQNO;
				tmp.BEGDA	 = DateUtil.toBasicString(place.BEGDA);
				tmp.ENDDA	 = DateUtil.toBasicString(place.ENDDA);
				tmp.LAND1	 = place.LAND1;
				tmp.LANDTX	 = place.LANDTX;
				tmp.LAGBN	 = place.LAGBN;
				tmp.BREN	 = place.BREN;
				tmp.del	 	 = place.del;
		
				arr.push(tmp);
			}
			return arr;
		} 		

		private function toSaveFormatMemberList(coll:ArrayCollection):Array
		{
			var arr:Array = new Array();
			for each(var vo:BizTripMemberVO in coll)
			{
				var tmp:Object = new Object;
				tmp.PERNR	 = vo.PERNR;
				tmp.BEGDA	 = DateUtil.toBasicString(vo.BEGDA);
				tmp.ENDDA	 = DateUtil.toBasicString(vo.ENDDA);
				tmp.ENAME	 = vo.ENAME;
				tmp.ORGTX	 = vo.ORGTX;
				tmp.JWTXT	 = vo.JWTXT;
				tmp.WDAY	 = vo.WDAY.toString();
				tmp.BIGO	 = vo.BIGO;
				arr.push(tmp);
			}
			return arr;
		} 		

 		private function toSaveFormatAdjustBase(vo:AdjustBaseVO):Array
		{
			var arr:Array = new Array();
			var tmp:Object = new Object;
			if(vo!=null) {
				tmp.KOSTL = vo.KOSTL;				// 코스트 센터
				tmp.WERT1 = vo.WERT1;				// 가용예산
				tmp.KDATE = DateUtil.toBasicString(vo.KDATE);				// 출장시작일
				trace("KDATE = " + tmp.KDATE + ", " + vo.KDATE);
				tmp.KURSF01 = vo.KURSF01;			// 환율
				tmp.KURSF02 = vo.KURSF02;			// 환율
				tmp.DAYPY = vo.DAYPY;				// 일비
				tmp.WAERS = vo.WAERS;				// 통화 키
				tmp.TRSTATUS = vo.TRSTATUS;			// 출장진행상태
				tmp.TRSTATX = vo.TRSTATX;			// 
				tmp.TRTEXT = vo.TRTEXT;				// 출장진행 오류메시지
			}
			arr.push(tmp);
			return arr;
		} 		
		
 		private function toSaveFormatCarfare(coll:ArrayCollection):Array
		{
			var arr:Array = new Array();
			for each(var vo:MemberCarfareVO in coll)
			{
				var tmp:Object = new Object;
				tmp.PERNR	 = vo.PERNR;		//	사원 번호
				tmp.TRTICH	 = vo.TRTICH;		//	지급여부
				
				tmp.PCARC	 = vo.PCARC;		//	개인차량이용
				tmp.OCARC	 = vo.OCARC;		//	회사차량이용
				tmp.TCARC	 = vo.TCARC;		//	동반차량이용
				tmp.DRIKM	 = vo.DRIKM.toString();		//	운행거리(KM)
				tmp.UNITAMT	 = vo.UNITAMT;	//	Km 당 단가
				tmp.PDRPY	 = vo.PDRPY.toString();		//	유류비
				tmp.WAERS	 = vo.WAERS;				//	통화 키
				tmp.DAYPY	 = vo.DAYPY;		//
				tmp.EGBN	 = vo.EGBN;
				trace("PERNR=" + tmp.PERNR + ", PCARC=" + tmp.PCARC +"DAYPY = " + tmp.DAYPY);
				arr.push(tmp);
			}
			return arr;
		} 		
		
 		private function toSaveFormatMemberDetailCost(coll:ArrayCollection):Array
		{
			var arr:Array = new Array();
			for each(var vo:MemberDetailCostVO in coll)
			{
				var tmp:Object = new Object;
				tmp.PERNR	 = vo.PERNR;		//	사원 번호
				tmp.SEQNO	 = vo.SEQNO;		//	순번
				tmp.CARDNO	 = vo.CARDNO;		//	카드번호
				tmp.APNO	 = vo.APNO;			//	승인번호
				tmp.RECGBN	 = vo.RECGBN;		//	증빙구분
				tmp.RECTXT	 = vo.RECTXT;		//	
				tmp.RDATE	 = DateUtil.toBasicString(vo.RDATE);		//	증빙일자
				tmp.MERNM	 = vo.MERNM;		//	가맹정명
				tmp.AMT	 = vo.AMT;				//	금액
				tmp.WAERS	 = vo.WAERS;		//	통화 키
				tmp.COSTGBN	 = vo.COSTGBN;		//	비용구분
				tmp.COSTEXT	 = vo.COSTEXT;		//	
				tmp.BIGO	 = vo.BIGO;			//	비고
				tmp.RBELNR	 = vo.RBELNR;		//	회계 전표 번호
				tmp.RBTEXT	 = vo.RBTEXT;		//	전표오류메세지
				tmp.USED_NO	 = vo.USED_NO;		//	전표오류메세지
				arr.push(tmp);

			}
			return arr;
		} 		
		private function collectionToArray(coll:ArrayCollection):Array
		{
			var arr:Array = new Array();
			for each(var rec:* in coll)
			{
				arr.push(rec.clone());
			}
			return arr;
		} 		

		private function buildAdjustDataPackage(memberAdjust:MemberAdjustVO):AdjustDataPackage
		{
			var dataPackage:AdjustDataPackage = new AdjustDataPackage;
			dataPackage.memberAdjust	= memberAdjust.clone();
			dataPackage.memberInfo 		= findMemberInfo(memberAdjust.PERNR);
			dataPackage.memberCarefare	= findCarfare(memberAdjust.PERNR);
			if(!dataPackage.memberCarefare) {
				dataPackage.memberCarefare = new MemberCarfareVO;
				dataPackage.memberCarefare.PERNR = memberAdjust.PERNR;
			}
			dataPackage.memberDetailCost = filterDetailCost(memberAdjust.PERNR);
			//dataPackage.
			//trace("buildAdjustDataPackage");
			return dataPackage;
		}
		
		private function findMemberInfo(pernr:String):BizTripMemberVO
		{
			for each(var member:BizTripMemberVO in view.memberList) {
				if(member.PERNR == pernr) return member;
			}
			var vo:BizTripMemberVO = new BizTripMemberVO();
			vo.PERNR = pernr;
			return vo;
		}
		
		private function findMemberAdjust(pernr:String):MemberAdjustVO
		{
			for each(var member:MemberAdjustVO in view.memberAdjustList) {
				if(member.PERNR == pernr) return member;
			}
			/*
			var vo:MemberAdjustVO = new MemberAdjustVO();
			vo.PERNR = pernr;
			vo.ENAME = vo.ENAME;
			return vo;
			*/
			return null;
		}
		
		private function findCarfare(pernr:String):MemberCarfareVO
		{
			for each(var carfare:MemberCarfareVO in memberCarfare) 
			{
				if(carfare.PERNR == pernr) {
					return carfare;
				}
			}
			/*
			var vo:MemberCarfareVO = new MemberCarfareVO();
			vo.PERNR = pernr;
			return vo;
			*/
			return null;
		}
		
		private function removeCarfare(pernr:String):void
		{
			for(var i:int=0; i<memberCarfare.length; i++) {
				if(memberCarfare.getItemAt(i).PERNR == pernr) {
					memberCarfare.removeItemAt(i);
					i--;
				}
			}
		}
		
		private function mergeCarfare(item:MemberCarfareVO):void
		{
			trace("get carfare: " + item.DAYPY);
			memberCarfare.addItem(item);
		}

		private function filterDetailCost(pernr:String):ArrayCollection
		{
			var arr:ArrayCollection = new ArrayCollection();
			for each(var member:MemberDetailCostVO in memberDetailCost) 
			{
				if(member.PERNR == pernr) {
					arr.addItem(member.clone());
				}
			}
			//trace("filterDetailCost: " + arr.length);
			return arr;
		}
		
		private function removeDetailCost(pernr:String):void
		{
			for(var i:int=0; i<memberDetailCost.length; i++) {
				if(memberDetailCost.getItemAt(i).PERNR == pernr) {
					memberDetailCost.removeItemAt(i);
					i--;
				}
			}
		}
		
		private function mergeDetailCost(arr:ArrayCollection):void
		{
			for each(var item:* in arr) {
				memberDetailCost.addItem(item);
			}
			arr.removeAll();
		}
		
		private function onConfirmAdjustInput(dataPackage:AdjustDataPackage):void
		{
			removeCarfare(dataPackage.memberInfo.PERNR);
			mergeCarfare(dataPackage.memberCarefare);
			
			
			var memberAdjust:MemberAdjustVO = findMemberAdjust(dataPackage.memberInfo.PERNR);
			if(!memberAdjust) {
				memberAdjust = new MemberAdjustVO;
				memberAdjust.PERNR = dataPackage.memberInfo.PERNR;
				memberAdjust.ENAME = dataPackage.memberInfo.ENAME;
			}
			memberAdjust.TRTICH = dataPackage.memberAdjust.TRTICH;
			memberAdjust.DAYPY = dataPackage.memberAdjust.DAYPY;
			
			// - 2013.06.11 j.t 추가 -
			memberAdjust.PCARC = dataPackage.memberAdjust.PCARC; // 개인 차량
			memberAdjust.OCARC = dataPackage.memberAdjust.OCARC; // 회사용 차량
			memberAdjust.TCARC = dataPackage.memberAdjust.TCARC; // 동승차량
			
			memberAdjust.DRIKM = dataPackage.memberAdjust.DRIKM;
			memberAdjust.PCAPY = dataPackage.memberAdjust.PCAPY;
			memberAdjust.EGBN =  dataPackage.memberAdjust.EGBN;
			
			/*
			memberAdjust.TRTICH = dataPackage.memberCarefare.TRTICH;
			if(memberAdjust.TRTICH=="X")
				memberAdjust.DAYPY	= dataPackage.memberCarefare.PDRPY;
			memberAdjust.PCARC = dataPackage.memberCarefare.PCARC;
			if(memberAdjust.PCARC=="X")
				memberAdjust.PCAPY = dataPackage.memberCarefare.PDRPY;
			*/
			memberAdjust.EATPY = sumPay(dataPackage.memberDetailCost, "02");
			memberAdjust.STYPY = sumPay(dataPackage.memberDetailCost, "03");
			memberAdjust.TRAPY = sumPay(dataPackage.memberDetailCost, "04");
			
			memberAdjust.DODPY = sumPay(dataPackage.memberDetailCost, "07");
			
			//trace(memberAdjust.EATPY + "," + memberAdjust.STYPY + ", " + memberAdjust.TRAPY);

			removeDetailCost(dataPackage.memberInfo.PERNR);
			mergeDetailCost(dataPackage.memberDetailCost);
			
			sumTotalAmount();
		}
		
		private function sumPay(src:ArrayCollection, code:String):Number
		{
			var amount:Number = 0;
			for each(var adjust:MemberDetailCostVO in src)
			{
				if( adjust.COSTGBN == code) {
					amount += adjust.AMT;
				}
			}		
			return amount;	
		}

		private function sumTotalAmount():void
		{
			var totalAmount:Number = 0;
			for each(var memAdjust:MemberAdjustVO in view.memberAdjustList)
			{
				totalAmount += memAdjust.sumN;
			}
			view.totalAmount =totalAmount;
		}



		private function setViewStatus(status:String):void
		{
			switch(view.summary.TRSTATUS) {
			case "11":	// 기본품의 기안
				view.viewStatus = CostsBizTrip.STATUS_EDITABLE_BASIC;		
				break;
			case "12":	// 기본품의 결재중
				view.viewStatus = CostsBizTrip.STATUS_READONLY_BASIC;
				break;
			case "13":	// 기본품의 결재완료
				view.summary.TRPAYC = "X";
				view.viewStatus = CostsBizTrip.STATUS_EDITABLE_ADJUST;
				break;
			case "14":	// 기본품의 반려
				view.viewStatus = CostsBizTrip.STATUS_EDITABLE_BASIC;	
				break;
			case "21":	// 정산 기안
				//20150225
				//view.viewStatus = CostsBizTrip.STATUS_EDITABLE_ADJUST; 
				view.viewStatus = CostsBizTrip.STATUS_EDITABLE_ALL;
				break;
			case "22":	// 정산 결재중
				view.viewStatus = CostsBizTrip.STATUS_READONLY_ALL;
				break;
			case "23":	// 정산 결재 완료
				view.viewStatus = CostsBizTrip.STATUS_READONLY_ALL;
				break;
			case "24":	// 정산  결재 반려
				view.viewStatus = CostsBizTrip.STATUS_EDITABLE_ADJUST;
				break;
			case "27":
				view.viewStatus = CostsBizTrip.STATUS_READONLY_ALL;
				break;
			default:
				view.viewStatus = CostsBizTrip.STATUS_EDITABLE_BASIC;		
				break;
			}
		}
		private function setViewStatus2(status:String):void
		{
			switch(view.summary.TRSTATUS) {
			case "11":	// 기본품의 기안
			case "12":	// 기본품의 결재중
			case "13":	// 기본품의 결재완료
			case "14":	// 기본품의 반려
				view.viewStatus = CostsBizTrip.STATUS_READONLY_BASIC;
				break;
				break;
			case "21":	// 정산 기안
			case "22":	// 정산 결재중
			case "23":	// 정산 결재 완료
			case "24":	// 정산  결재 반려
			case "27":
			default:
				view.viewStatus = CostsBizTrip.STATUS_READONLY_ALL;		
				break;
			}
		}
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():CostsBizTrip
        {
            return viewComponent as CostsBizTrip;
        }
		
		
	}
}